#### Figure 2: Norm Violations and Violence Support (By Party) ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

violence_ind = paste0("violence",1:6,"re")
norm_ind = paste0("norm_",c("judges","polling","censorship","loyalty"),"re")

cs_summary = data_pnas |> 
  filter(pid %in% c("Democrat","Republican")) |> # Just D/R
  select(pid, all_of(c(violence_ind, norm_ind)),
         uid, weight) |> 
  pivot_longer(-c("pid","uid","weight"), names_to = "var", values_to = "val") |> 
  as_survey_design(ids = uid, weights = weight) |> 
  group_by(pid, var) |> 
  summarise(val_sum = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup()  |> 
  filter(var != "violence1re") |>
  filter(var != "violence2re") |> 
  filter(var != "norm_executivere") |> 
  mutate(var_typ = ifelse(str_detect(var,"norm"), "Democratic Norms", "Violence"),
         var = recode_factor(var,
                             norm_pollingre = "Reduce outparty polling stations",
                             norm_loyaltyre = "More loyal to party than Constitution\nin contested elections",
                             norm_judgesre = "Ignore outparty court decisions",
                             norm_executivere = "President should circumvent Congress",
                             norm_censorshipre = "Censor partisan media",
                             violence6re = "Murder",
                             violence5re = "Assault with deadly weapon",
                             violence4re = "Arson",
                             violence3re = "Assault",
                             violence2re = "Vandalism",
                             violence1re = "Protest without\npermit")
  )

fig_2a = cs_summary |> 
  ggplot(aes(x = val_sum, 
             y = tidytext::reorder_within(var, val_sum, var_typ),
             group = pid,
             label = paste0(round(val_sum,3)*100,"%"))) +
  geom_pointrange(aes(xmin = val_sum_low,
                      xmax = val_sum_upp,
                      color = pid),
                  position = position_dodge(.75), size=.4) +
  geom_text(aes(x = val_sum + .13),
            position = position_dodge(.75), size=3) +
  facet_wrap(~ var_typ, scales = "free_y", ncol=1) +
  force_panelsizes(rows = c( 1,.75)) +
  scale_color_manual(name = "Party",
                     values = c("blue","red")) +
  scale_x_continuous(labels = scales::percent,
                     limits = c(0,1)) +
  tidytext::scale_y_reordered() +
  labs(x = "Percent Support",
       y = NULL) +
  theme_prl(base_family = "Helvetica") +  
  theme( strip.text.x = element_text(size = 8),
         panel.spacing.y = unit(0, "lines"),
         legend.position = "none")

ot_norms = data_pnas |> 
  filter(pid %in% c("Democrat","Republican")) |> 
  mutate(week = floor_date(date-2, unit = "week"), # - 2 so weeks start on Friday (survey start)
         weight = weight * wt_adj) |> # re-adjust weight, since we aren't pooling over a cross-section
  select(pid, week, all_of(norm_ind), uid, weight) |> 
  pivot_longer(all_of(norm_ind), names_to = "var", values_to = "val") |> 
  mutate(var = recode_factor(var,
                             norm_pollingre = "Reduce outparty\npolling stations",
                             norm_loyaltyre = "More loyal to party\nthan Constitution\nin contested elections",
                             norm_judgesre = "Ignore outparty\ncourt decisions",
                             norm_executivere = "President should\ncircumvent congress",
                             norm_censorshipre = "Censor partisan media"))

fig_2b = ot_norms |> 
  ggplot(aes(x = week, y = val, group = pid, color = pid)) +
  geom_smooth(weight = "weight") +
  facet_wrap(~ var, ncol = 2) +
  scale_x_date(date_labels = "%b %Y",
               date_breaks = "4 month") +
  scale_y_continuous(labels = scales::percent,
                     breaks = c(.1,.15,.2)) +
  scale_color_manual(name = "Party",
                     values = c("blue","red")) +
  labs(x = NULL, y = "Estimated Support") +
  theme_prl(base_family = "Helvetica") +
  theme(axis.text.x = element_text(angle = 0, hjust = 1, vjust = 1, size = 8)) +
  guides(color = guide_legend(override.aes = list(fill = NA),
                              title.position = 'left')) +
  theme(legend.position = c(0.8, 0.095),
        legend.direction="vertical",
        legend.key = element_rect(fill = "transparent"),
        legend.background = element_rect(fill = 'transparent'))

fig_2 = cowplot::plot_grid(fig_2a, fig_2b, ncol = 1, rel_heights = c(.9,.9), labels=c("A.","B."))

print(fig_2)

ggsave(here("Plots","Main","figure_2.pdf"),
       fig_2,
       units = "in",
       width = 5, height = 7,
       dpi = 600)